"use strict";
/* Controllers */
app.controller("smartDqController", ['$scope', '$location', '$rootScope', '$routeParams', 'smartDqService', function ($scope, $location, $rootScope, $routeParams, smartDqService) {

    var vm = $scope.vm = {};
    vm.result = {};
    vm.p = {};
    vm.c = {};
    vm.p.id = $routeParams.id; //

    vm.c.table = 'dmv_zp_n_bn_ent_info2';
    vm.c.dt = hllCurrentDt(-1);
    vm.c.dims = [
        {'column':'biz', 'text':'biz'},
        {'column':'platform', 'text':'platform'},
        {'column':'slot', 'text':'slot'}
    ];
    vm.c.indexs = [
        {'column':'userid', 'text':'count(distinct userid) as uv'},
        {'column':'has_im', 'text':'sum(has_im) as im_total'},
        {'column':'has_delivery', 'text':'sum(has_delivery) as delivery_cnt'}
        ];
    vm.c.filters = [
        {'column':'info_cate3', 'text':'info_cate3 in(574,234)'},
        {'column':'info_local1', 'text':'info_local1 in(1,2,3)'}
        ];

    vm.c.selected = 'dim'
    vm.c.sql = '';


    $scope.searchQuery = function() {
        $scope.loadUrl();
    }

    var errorFn = function (result) {
        alert(result);
    };

    $scope.loadUrl = function () {
        var vm = $scope.vm;
        // 请求后台
        vm.result.ms = "...";
        var param = { search: vm.p.search };
        var procFn = function (response) {
            var data = response.data;
            if (data == null) {
                return;
            }
            var treeData = function (data) {
                return data;
            }

            var addOnlyItem = function(arr, it) {
                for(var i in arr) {
                    if(arr[i].column==it) {
                        if(arr[i].text=='') {//删除后的恢复
                            arr[i].text=it;
                        }
                        return;
                    }
                }
                arr.push({'column':it,'text':it});
            }

            $('#tree').treeview({
                data: treeData(data),
                levels: 2, // 显示层级
                onNodeSelected: function (event, data) {
//                    alert("selected： " + data.text);
                    if(data.type=='table') {
                        console.log("table: " + data.text);
                        vm.c.table = data.tableName;
                    }
                    if(data.type=='column') {
                        console.log("column: " + vm.c.selected + ', ' + data.text);
                        switch(vm.c.selected) {
                        case 'dim':
                            addOnlyItem(vm.c.dims, data.columnName);
                            break;
                        case 'ind':
                            addOnlyItem(vm.c.indexs, data.columnName);
                            break;
                        case 'filter':
                            addOnlyItem(vm.c.filters, data.columnName);
                            break;
                        default:
                            alert('unknown selected.');
                            break;
                        }
                    }
                    $scope.$apply();
                }
            });
        };
        smartDqService.searchTableTree(param, procFn, errorFn);
    };

    $scope.changeIt = function(type, data) {
        var vm = $scope.vm;

        var delOnlyItem = function(arr, it) {
            var result=[];
            for(var i in arr) {
                if(arr[i].column==it) {
                    continue;
                }
                result.push(arr[i]);
            }
            return result;
        }
        switch(type) {
        case 'dim':
            if(confirm(data.column+"是否删除维度？")){
                data.text = '';
                vm.c.dims = delOnlyItem(vm.c.dims, data.column);
            }
            break;
        case 'ind':
            var info = prompt("请输入"+data.column+"聚合处理:", data.text);
            if(info==null) {// cancel
                return;
            }
            if(info=='') {
                data.text='';
                vm.c.indexs = delOnlyItem(vm.c.indexs, data.column);
            }else {
                data.text= info;
            }
            break;
        case 'filter':
            var info = prompt("请输入"+data.column+"过滤处理:", data.text);
            if(info==null) {// cancel
                return;
            }
            if(info=='') {
                vm.c.filters = delOnlyItem(vm.c.filters, data.column);
            } else{
                data.text= info;
            }
            break;
        default:
            alert('unknown type.');
            break;
        }

    }

    $scope.smartSql = function () {
        var vm = $scope.vm;
        var dim = '';
        for(var it in vm.c.dims) {
            if(vm.c.dims[it].text=='') {
                continue;
            }
            if(dim.length>0) {
                dim += ', ';
            }
            dim += ('\n    ' +vm.c.dims[it].text);
        }
        var ind = '';
        for(var it in vm.c.indexs) {
            if(vm.c.indexs[it].text=='') {
                continue;
            }
            if(ind.length>0) {
                ind += ', ';
            }

            ind += ('\n    ' + vm.c.indexs[it].text);
        }

        var filter = '';
        for(var it in vm.c.filters) {
            if(vm.c.filters[it].text=='') {
                continue;
            }
            if(filter.length>0) {
                filter += ' and ';
            }
            filter += ('\n    ' + vm.c.filters[it].text);
        }

        vm.c.sql = [
            '-- smart create ',
            '\n'+'select', dim+',', ind,
            '\n'+'from', vm.c.table,
            '\n'+'where', 'dt=', vm.c.dt,' and', filter,
            '\n'+'group by', dim
        ].join(' ');

    }

    $scope.initializeController = function () {
        vm.result.ms = '';
        $scope.loadUrl();
    };

    $scope.initializeController();





}]);


/* Services */
app.service('smartDqService', ['ajaxService', function (ajaxService) {
    this.searchTableTree = function (params, successFunction, errorFunction) {
        ajaxService.AjaxPost(params, "/star/api/basic-service/v1/smartdq/searchTableTree.do", successFunction, errorFunction);
    };
}]);


